function clearDiv(dom) {
	while (dom.lastChild) {
		dom.removeChild(dom.lastChild);
	}
}

function dyalogInit() {
	parcel.messages = [];
	parcel.currentUid = 0;
	parcel.activeUploads = {};
}

function dyalogSelect(uid) {
	parcel.currentUid = uid;
	let unreadChip = document.querySelector(`[data-uid="${uid}"][data-key="unreadCount"]`);
	unreadChip.innerText = 0;
	unreadChip.classList.add('hidden');
	let uploadBox = document.getElementById('uploadbox');
	let uploadName = document.getElementById('uploadFilename');
	if (parcel.activeUploads[uid]) {
		uploadBox.classList.remove('hidden');
		uploadName.innerText = parcel.activeUploads[uid];
	} else {
		uploadBox.classList.add('hidden');
	}
	dyalogRender();
}

function dyalogAppend(uid, msg, isSelf = false) {
	let arr = parcel.messages[uid] || [];
	try {
		msg.isSelf = isSelf;
		arr.push(msg);
		parcel.messages[uid] = arr;
		if (uid === parcel.currentUid || uid === parcel.uid) {
			dyalogRender();
		} else {
			if (!isSelf)
				dyalog_chip_add(uid);
		}
	} catch (e) {
		console.log(e);
		toast('收到了无效的信息');
	}
}

function dyalog_chip_add(uid) {
	let chip = document.querySelector(`[data-uid="${uid}"][data-key="unreadCount"]`);
	if (chip) {
		chip.parentElement.classList.remove('hidden');
		try {
			let count = Number(chip.innerText);
			++count;
			chip.innerText = count;
		} catch (e) {
			console.log(e);
		}
	} else {
		console.log(`stranger: ${uid}`);
	}
}

function dyalogRender() {
	let msgBox = document.getElementById('messages');
	clearDiv(msgBox);
	if (parcel.currentUid === 0) {
		let wrapper = document.createElement('div');
		wrapper.className = 'absolute-centering';
		wrapper.innerText = '从左侧选择联系人';
		msgBox.appendChild(wrapper);
	} else {
		let dialogs = parcel.messages[parcel.currentUid];
		if (dialogs && dialogs.length > 0) {
			let bubble = undefined;
			dialogs.sort((a, b) => a.time - b.time).forEach(entry => {
				bubble = generate_bubble(entry);
				msgBox.appendChild(bubble);
			});
			if (bubble != null) {
				bubble.scrollIntoView(false);
			}
		}
	}
}

function dyalogSelectFile() {
	return new Promise((resolve, reject) => {
		let input = document.createElement('input');
		input.type = 'file';
		input.onchange = () => {
			let files = input.files;
			if (files) {
				let file = files[0];
				if (file) {
					resolve(file);
				} else {
					reject();
				}
			}
		};
		input.click();
	});
}

function generate_bubble(msgObj) {
	let row = document.createElement('div');
	row.className = 'dyalog-row';
	let data = msgObj.data;
	if (data instanceof Array) {
		let cell = document.createElement('div');
		let pad = document.createElement('div');
		pad.className = 'dyalog-padder';
		cell.className = 'dyalog-bubble';
		for (let datum of data) {
			cell.appendChild(generate_bubble_populator(datum));
		}
		if (msgObj.isSelf) {
			cell.classList.add('dyalog-bubble--outbound');
			row.appendChild(pad);
			row.appendChild(cell);
		} else {
			cell.classList.add('dyalog-bubble--inbound');
			row.appendChild(cell);
			row.appendChild(pad);
		}
	} else {
		if (data.type === 8) {
			document.querySelectorAll(`[uid='${parcel.currentUid}']`).forEach(it => it.innerText = 'Online');
		} else {
			let cell = document.createElement('div');
			let pad = document.createElement('div');
			pad.className = 'dyalog-padder';
			cell.className = 'dyalog-bubble';
			cell.appendChild(generate_bubble_populator(data));
			if (msgObj.isSelf) {
				cell.classList.add('dyalog-bubble--outbound');
				row.appendChild(pad);
				row.appendChild(cell);
			} else {
				cell.classList.add('dyalog-bubble--inbound');
				row.appendChild(cell);
				row.appendChild(pad);
			}
		}
	}
	return row;
}

function generate_bubble_populator(data) {
	let span = document.createElement('span');
	let link = document.createElement('a');
	let linkPieces;
	if (data.type <= 4) {
		linkPieces = data.content.split('\r\n');
	} else {
		linkPieces = data.data.split('\r\n');
	}
	// todo: get more types working
	switch (data.type) {
		case 0: // plain text
			span.appendChild(document.createTextNode(data.content));
			return span;
		case 1: // @
			break;
		case 2: // link
			link.innerText = linkPieces[0];
			link.href = linkPieces[1];
			span.appendChild(link);
			return span;
		case 3: // emote
			break;
		case 4: // raw html
			let frame = document.createElement('iframe');
			frame.src = `data:text/html;charset=utf-8,${data.content}`;
			frame.sandbox = 'allow-scripts';
			return frame;
		case 5: // picture
			break;
		case 6: // voice
			break;
		case 7: // file
			let downloadPercentage = document.createElement('span');
			link.innerText = `文件分享：${linkPieces[0]}`;
			link.href = '#';
			link.onclick = (e) => {
				e.preventDefault();
				downloadFile(downloadPercentage, linkPieces[0], linkPieces[1]);
			};
			span.appendChild(link);
			span.appendChild(downloadPercentage);
			return span;
		case 8: // status change
			return '';
		default: // debug msg, maybe?
			span.innerText = JSON.stringify(data);
			return span;
	}
}
